package com.weixing.mall.provider.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.core.enums.OrderAppTagEnum;
import com.weixing.mall.core.enums.OrderSysTagEnum;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.api.model.enums.AgentTypeEnum;
import com.weixing.mall.provider.api.model.enums.OrderTypeEnum;
import com.weixing.mall.provider.api.service.SubSiteRPC;
import com.weixing.mall.provider.mapper.LeaderShowMapper;
import com.weixing.mall.provider.model.enums.*;
import com.weixing.mall.provider.model.query.*;
import com.weixing.mall.provider.model.vo.OrderShowVo;
import com.weixing.mall.provider.service.ILeaderReportService;
import com.weixing.mall.util.SKUUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 0202
 * @date 2020-5-29
 */
@Service
public class LeaderReportServiceImpl implements ILeaderReportService {
    @Autowired
    private LeaderShowMapper leaderShowMapper;
    @Autowired
    private SubSiteRPC subSiteRPC;

    @Override
    public Map<String, Object> indexDataTotal(String startTime,String endTime) {
        Map map = new HashMap<String,Object>();
        //销售总量 客服审核通过
        map.put("saleQuantity",leaderShowMapper.orderSaleTotalForLeader(OrderStateEnum.REJECT.getValue(),null,startTime,endTime));
        //销售总金额 客服审核通过
        map.put("saleAmount",leaderShowMapper.saleAmountTotalForLeader(OrderStateEnum.REJECT.getValue(),startTime,endTime));
        //库存总量  app仓 + erp仓 （sql限制）
        map.put("stock",leaderShowMapper.stockTotalForLeader());
        //发货数量  发货记录表
        map.put("sendQuantity",leaderShowMapper.shippedTotalForLeader(startTime,endTime));
        //客服审单 取全部客服审核通过的单
        map.put("examQuantity",leaderShowMapper.customerTotalForLeader(OrderStateEnum.REJECT.getValue(),startTime,endTime));
        //代理商开户数量 一段时间内的代理开户数量(不控制是否绑定是否启用)
        map.put("dailiQuantity",leaderShowMapper.agentTotal(null,null,null,startTime,endTime));
        //全部商品信息不限制上下架 不限时间 限制待删除
        map.put("goodsQuantity",leaderShowMapper.goodsTotal(null,null));
       // map.put("memberQuantity",leaderShowMapper.memberTotal(startTime,endTime));
        //（客户数量）新的会员数量是指订单收货人  订单地址按手机号进行统计
        map.put("memberQuantity",leaderShowMapper.memberTotalOrderAddress(startTime,endTime));
        //（广告预约量）广告数量指的是预约的数量 包含（已付款、已排版、已投放）
        map.put("adsQuantity",leaderShowMapper.adsTotal(startTime,endTime));
        return map;
    }

    @Override
    public Map<String, Object> getSaleHb() {
        Map map = new HashMap<String,Object>();
        map.put("thisYear",leaderShowMapper.thisYear());
        map.put("lastYear",leaderShowMapper.lastYear());
        return map;
    }

    @Override
    public Map<String, Object> getSaleTb() {
        Map map = new HashMap<String,Object>();
        map.put("thisMonth",leaderShowMapper.thisMonth());
        map.put("lastMonth",leaderShowMapper.lastMonth());
        return map;
    }

    @Override
    public List<Map<String,Object>> getZqList(String startTime, String endTime) {
        return leaderShowMapper.partitionSaleTotalList( startTime, endTime);
    }

    @Override
    public  List<Map<String,Object>> getActivityList(String startTime, String endTime,Integer actType) {
        return leaderShowMapper.actSaleTotalList( startTime, endTime,actType);
    }

    @Override
    public Map<String, Object> getStockReport(LeaderStockQuery leaderStockQuery) {
        LeaderStockQuery lsq=new LeaderStockQuery();
        Long erpTotal = 0L;
        Long appTotal = 0L;
        Map map = new HashMap<String,Object>();
        if(ObjectUtil.isNotEmpty(leaderStockQuery)
                && ObjectUtil.isNotEmpty(leaderStockQuery.getDepotCode())
                && leaderStockQuery.getDepotCode().equals(GlobalConstant.DepotCode.ERP)){
            erpTotal = leaderShowMapper.stockTotal(leaderStockQuery);
        }else{
            lsq.setDepotCode(GlobalConstant.DepotCode.ERP);
            erpTotal = leaderShowMapper.stockTotal(lsq);
        }
        if(ObjectUtil.isNotEmpty(leaderStockQuery)
                && ObjectUtil.isNotEmpty(leaderStockQuery.getDepotCode())
                && leaderStockQuery.getDepotCode().equals(GlobalConstant.DepotCode.APP)){
            appTotal = leaderShowMapper.stockTotal(leaderStockQuery);
        }else{
            lsq.setDepotCode(GlobalConstant.DepotCode.APP);
            appTotal = leaderShowMapper.stockTotal(lsq);
        }

       // map.put("stockQuantity",leaderShowMapper.stockTotal(""));
        map.put("stockQuantity",erpTotal+appTotal);//客户逻辑 总计只统计ERP和APP的总和
        map.put("erpQuantity",erpTotal);
        map.put("appQuantity",appTotal);
        return map;
    }

    @Override
    public IPage<Map<String, Object>> getStockList(Page page,LeaderStockQuery leaderStockQuery) {
        return leaderShowMapper.getStockList(page,leaderStockQuery);
    }

    @Override
    public Map<String, Object> getReportForFinancial(String startTime, String endTime) {
        Map map = new HashMap<String, Object>();
        //销售总数
        Long saleQuantity = leaderShowMapper.orderSaleTotalForLeader(OrderStateEnum.REJECT.getValue(),null,startTime, endTime);
        //销售利润
        BigDecimal saleLirun = BigDecimal.ZERO;
        //销售成本
        BigDecimal saleCost = leaderShowMapper.saleCostTotalForFinancial(OrderStateEnum.REJECT.getValue(),startTime,endTime);
        //总销售额
        BigDecimal saleTotalAmount = leaderShowMapper.saleAmountTotalForFinancial(OrderStateEnum.REJECT.getValue(),startTime,endTime);
        if(saleTotalAmount != null && saleCost != null){
            saleLirun = saleTotalAmount.subtract(saleCost);
        }
        //销售正价总数
        Long saleNormalQuantity = leaderShowMapper.orderSaleTotalForLeader(OrderStateEnum.REJECT.getValue(), OrderTypeEnum.NORMAL.getValue(),startTime, endTime);
        Long saleAgentQuantity = leaderShowMapper.orderSaleTotalForLeader(OrderStateEnum.REJECT.getValue(), OrderTypeEnum.AGENT.getValue(),startTime, endTime);
        Long saleSeckillQuantity = leaderShowMapper.orderSaleTotalForLeader(OrderStateEnum.REJECT.getValue(), OrderTypeEnum.SECKILL.getValue(),startTime, endTime);
        map.put("saleQuantity",saleQuantity);
        map.put("saleLirun",saleLirun);
        map.put("saleCost",saleCost);
        map.put("saleTotalAmount",saleTotalAmount);
        map.put("saleNormalQuantity",saleNormalQuantity);
        map.put("saleAgentQuantity",saleAgentQuantity);
        map.put("saleSeckillQuantity",saleSeckillQuantity);
        return map;
    }

    @Override
    public List<Map<String, Object>> categorySaleTop5(String startTime, String endTime) {
        //总销售额
        BigDecimal saleTotalAmount = leaderShowMapper.saleAmountTotalForFinancial(OrderStateEnum.REJECT.getValue(),startTime,endTime);
        //审核通过的
        List<Map<String,Object>> list = leaderShowMapper.categorySaleTop5(OrderStateEnum.REJECT.getValue(),startTime,endTime);
        for (Map<String,Object> map:list) {
            if(saleTotalAmount != null && ObjectUtil.isNotEmpty(map.get("saleAmount"))){
                BigDecimal saleAmount =new BigDecimal(map.get("saleAmount").toString());
                //占总销售额的比例
                BigDecimal percentage =  saleAmount.divide(saleTotalAmount,3,BigDecimal.ROUND_HALF_UP);
                //百分比
                map.put("hbData",percentage.multiply(new BigDecimal(100)));
            }else{
                map.put("hbData",BigDecimal.ZERO);
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> goodsSaleTop5(String startTime, String endTime) {
        return leaderShowMapper.goodsSaleTop5(startTime,endTime);
    }

    @Override
    public List<Map<String, Object>> provinceSaleTop10(String startTime, String endTime) {
        return leaderShowMapper.provinceSaleTop10(startTime,endTime);
    }

    @Override
    public List<Map<String, Object>> citySaleTop10(String startTime, String endTime) {
        return leaderShowMapper.citySaleTop10(startTime,endTime);
    }

    @Override
    public IPage<Map<String, Object>> areaSaleList(Page page, String startTime, String endTime, String cityName) {
        IPage<Map<String,Object>> list = leaderShowMapper.areaSaleList(page,startTime,endTime,cityName);
        if(list.getRecords() != null && list.getRecords().size()>0){
            List<Map<String,Object>> listOp = list.getRecords();
            listOp.forEach(map->{
               if(ObjectUtil.isNotEmpty(map.get("saleNum"))&& ObjectUtil.isNotEmpty(map.get("refundNum"))){
                   BigDecimal saleNum = new BigDecimal(map.get("saleNum").toString());
                   BigDecimal refundNum = new BigDecimal(map.get("refundNum").toString());
                   //退货的比例
                   BigDecimal percentage =  refundNum.divide(saleNum,2,BigDecimal.ROUND_HALF_UP);
                   //百分比
                   map.put("refundPercentage",percentage.multiply(new BigDecimal(100)));
               }else{
                   map.put("refundPercentage",BigDecimal.ZERO);
               }
            });
        }
        addSerialNum(page,list);
        return list;
    }

    private IPage<Map<String, Object>> addSerialNum(Page page,IPage<Map<String, Object>> list){
        int i=1;
        for (Map<String, Object> m:list.getRecords()){
            //计算序号  序号等于 （页数-1）*10+i
            m.put("serialNum",(page.getCurrent()-1)*10 + i);
            i++;
        }
        return list;
    }

    @Override
    public Map<String, Object> getReportForShipped(String startTime, String endTime) {
        Map map = new HashMap<String,Object>();
        //发货员取消数量  采用productStatus、时间、客服确认通过的 限制
        map.put("cancelQuantity",leaderShowMapper.canceledOrderTotal(ProductStatusEnum.STATUS7.getValue(), NoSuppllyAuditEnum.TYPE_1.getValue(),startTime, endTime));
        //发货员断货数量  采用productStatus、时间、客服确认通过的 限制
        map.put("curtOffQuantity",leaderShowMapper.outStockOrderTotal(ProductStatusEnum.STATUS6.getValue(),NoSuppllyAuditEnum.TYPE_1.getValue(),startTime, endTime));
        //发货员待货数量  采用productStatus、时间 限制
        map.put("waitQuantity",leaderShowMapper.waitOrderTotal(ProductStatusEnum.STATUS2.getValue(),startTime, endTime));
        //发货员待定数量  采用productStatus、时间 限制
        map.put("bePendQuantity",leaderShowMapper.waitConfirmedOrderTotal(ProductStatusEnum.STATUS1.getValue(),startTime, endTime));
        //发货员退货数量  采用退货类型控制、售后结果不为null即是入库、时间(更新时间) 限制
        map.put("backQuantity",leaderShowMapper.refundedOrderTotal(startTime, endTime));
        //发货总量 订单发货记录表 受时间限制
        map.put("sendQuantity",leaderShowMapper.shippedOrderTotal(startTime, endTime));
        return map;
    }

    @Override
    public List<Map<String, Object>> shippedChartTotalList(String startTime, String endTime) {
        //以订单发货记录表为准
        return leaderShowMapper.shippedChartTotalList(startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> outStockChartTotalList(String startTime, String endTime) {
        //断货状态  客服确认通过的 断货时间
        return leaderShowMapper.outStockChartTotalList(ProductStatusEnum.STATUS6.getValue(),NoSuppllyAuditEnum.TYPE_1.getValue(),startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> refundedChartTotalList(String startTime, String endTime) {
        //退货类型  售后结果不为null即是质检入库 时间（更新时间）
        return leaderShowMapper.refundedChartTotalList(startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> canceledChartTotalList(String startTime, String endTime) {
        //发货员取消    获取取消  客服确认通过  时间
        return leaderShowMapper.canceledChartTotalList(ProductStatusEnum.STATUS7.getValue(),NoSuppllyAuditEnum.TYPE_1.getValue(),startTime, endTime);
    }

    @Override
    public Map<String, Object> shipperPartitionChartTotalList(String startTime, String endTime) {
        //获取所有子站
        List<Map<String,Object>> sslist = subSiteRPC.getSubSiteList();
        //返回值封装（应前端要求封装数据格式）
        Map<String, Object> returnMap = new HashMap<>();
        //柱状图数据
        List<Map<String, Object>> list = leaderShowMapper.shipperPartitionChartTotalList(startTime, endTime);
        if(sslist == null|| sslist.size() == 0 || list == null || list.size() == 0){
            returnMap.put("categories", Lists.newArrayList());
            returnMap.put("series", Lists.newArrayList());
            return  returnMap;
        }
        //发货员对应专区的值的集合
        List<Map<String, Object>> series = Lists.newArrayList();
        //发货员集合封装（每个发货员包含所有子站值）
        list.forEach(mapData -> {
            //判断是否已创建发货员初始数据
            boolean flag = true;
            for(Map<String,Object> map1:series){
                //循环判断是否已创建数据若创建则修改对应数据值
                if(ObjectUtil.isNotEmpty(mapData.get("shipper_id"))&&map1.get("id").toString().equals(mapData.get("shipper_id").toString())){
                    //专区值集合
                    List<Map<String,Object>> dataList =  (List<Map<String,Object>> )map1.get("dataList");
                    dataList.forEach(map2 -> {
                        if(ObjectUtil.isNotEmpty(mapData.get("partition_id"))&&map2.get("id").toString().equals(mapData.get("partition_id").toString())){
                            map2.put("data",mapData.get("orderNum"));
                        }
                    });
                    flag = false;
                    break;
                }
            }
           //初始化专区值
            if(flag){
                //创建发货员map
                Map<String,Object> shipMap = new HashMap<>();
                shipMap.put("id",mapData.get("shipper_id"));
                shipMap.put("name",mapData.get("shipperName"));
                //专区值集合
                List<Map<String,Object>> dataList = Lists.newArrayList();
                for(Map<String,Object> ss:sslist){
                    //专区值
                    Map<String,Object> value = new HashMap<>();
                    if(ObjectUtil.isNotEmpty(mapData.get("partition_id"))&&ss.get("id").toString().equals(mapData.get("partition_id").toString())){
                        value.put("id",ss.get("id"));
                        value.put("data",mapData.get("orderNum"));
                    }else{
                        value.put("id",ss.get("id"));
                        value.put("data",0);
                    }
                    dataList.add(value);
                }
                shipMap.put("dataList",dataList);
                //新创建初始化数据 加入发货员集合中
                series.add(shipMap);
            }
        });
        //子站名字集合
        List<String> ssNameList = sslist.stream().map(map -> map.get("name").toString()).collect(Collectors.toList());
        //发货员对应专区数据集合
        series.forEach(map -> {
            //专区值集合
            List<Map<String,Object>> dataList =  (List<Map<String,Object>>)map.get("dataList");
            List<Integer> valueList = dataList.stream().map(map1 -> Integer.valueOf(map1.get("data").toString())).collect(Collectors.toList());
            map.put("data",valueList);
            map.remove("dataList");
            map.remove("id");
        });
        returnMap.put("categories", ssNameList);
        returnMap.put("series", series);
        return returnMap;
    }

    @Override
    public IPage<Map<String, Object>> shipperTotalList(Page page, String startTime, String endTime) {
        //以发货记录表为准
        IPage<Map<String, Object>> list = leaderShowMapper.shipperTotalList(page, startTime, endTime);
        addSerialNum(page,list);
        return list;
    }

    @Override
    public Map<String, Object> getKeFuReport(Long customerId,String startTime, String endTime) {
        Map map = new HashMap<String,Object>();
        //客服审核通过的订单
        map.put("auditQuantity",leaderShowMapper.auditOrderTotal(OrderStateEnum.REJECT.getValue(),customerId,startTime, endTime));
        //客服下单数
        map.put("placeOrderQuantity",leaderShowMapper.placeOrderTotal(customerId, OrderFromEnum.CUSTOMER.getValue(),startTime, endTime));
        //代理开户数量  （不限是否绑定是否启用）
        map.put("agentQuantity",leaderShowMapper.agentTotal(customerId,null,null,startTime, endTime));
        //代理商续费数量  时间
        map.put("agentRenewQuantity",leaderShowMapper.agentRenewTotal(customerId,startTime, endTime));
        return map;
    }

    @Override
    public List<Map<String, Object>> kefuSaleAmountTotalList(String startTime, String endTime) {
        //第三版sql 限制客服id不为空  货品状态不是断货和取消（6、7） 订单不是售后退货订单（null or 2）   时间限制
        return leaderShowMapper.kefuSaleAmountTotal(startTime, endTime);
    }

    @Override
    public Map<String, Object> getAgentReport() {
        Map map = new HashMap<String,Object>();
        //可用的 正式代理商 和 试用的代理商 sql限制 0、1 试用和正式
        map.put("totalQuantity",leaderShowMapper.agentSyntheticalReport(null,null, null));
        map.put("teamQuantity",leaderShowMapper.agentSyntheticalReport("findTeam",null, null));
        //可用的 经销商  金级
        map.put("goldQuantity",leaderShowMapper.agentSyntheticalReport(null, AgentLevelEnum.DEALER.getValue(), AgentTypeEnum.GOLD.getValue()));
        //可用的 经销商  银级
        map.put("silverQuantity",leaderShowMapper.agentSyntheticalReport(null, AgentLevelEnum.DEALER.getValue(), AgentTypeEnum.SILVER.getValue()));
        //可用的 一级代理商  金级
        map.put("goldFirstQuantity",leaderShowMapper.agentSyntheticalReport(null, AgentLevelEnum.LEVEL_1.getValue(), AgentTypeEnum.GOLD.getValue()));
        //可用的 一级代理商  银级
        map.put("silverFirstQuantity",leaderShowMapper.agentSyntheticalReport(null, AgentLevelEnum.LEVEL_1.getValue(), AgentTypeEnum.SILVER.getValue()));
        return map;
    }

    @Override
    public List<Map<String, Object>> agentLevelDistribution() {
        List<Map<String, Object>> list = leaderShowMapper.agentLevelDistribution();
        list.forEach(map -> {
            if(map.get("agent_level")!=null){
                Integer level = Integer.valueOf(map.get("agent_level").toString());
                switch (level){
                    case 1:
                        map.put("name","经销商");
                        break;
                    case 2:
                        map.put("name","一级代理商");
                        break;
                    case 3:
                        map.put("name","二级代理商");
                        break;
                    case 4:
                        map.put("name","三级代理商");
                        break;
                    default:
                        map.put("name","");
                        break;
                }
            }else {
                map.put("name","");
            }
            map.remove("agent_level");
        });
        return list;
    }

    @Override
    public List<Map<String, Object>> getAgentSaleList(String startTime, String endTime) {
        return leaderShowMapper.getAgentSaleList(startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> getTeamSaleList(String startTime, String endTime) {
        return leaderShowMapper.getTeamSaleList(startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> getAgentAreaList() {
        return leaderShowMapper.getAgentAreaList();
    }

    @Override
    public IPage<Map<String, Object>> getMemberReport(Page page, LeaderMemberQuery leaderMemberQuery) {
        return leaderShowMapper.getMemberReport(page,leaderMemberQuery);
    }

    @Override
    public IPage<Map<String, Object>> getBuyReport(Page page, LeaderMemberQuery leaderMemberQuery) {
        return leaderShowMapper.getBuyReport(page,leaderMemberQuery);
    }

    @Override
    public List<Map<String, Object>> getGoodsSaleListTop20(String startTime, String endTime) {
        return leaderShowMapper.getGoodsSaleListTop20(startTime, endTime);
    }

    @Override
    public IPage<Map<String, Object>> getGoodsSaleList(Page page, LeaderGoodsQuery leaderGoodsQuery) {
        IPage<Map<String, Object>> list = leaderShowMapper.getGoodsSaleList(page,leaderGoodsQuery);
        addSerialNum(page,list);
        return list;
    }

    @Override
    public List<Map<String, Object>> getSaleSKuList(LeaderGoodsQuery leaderGoodsQuery) {
        return leaderShowMapper.getSaleSKuList(leaderGoodsQuery);
    }

    @Override
    public Map<String, Object> getSaleReport(LeaderSaleQuery lsq) {
        Map map = new HashMap<String,Object>();
        Map<String,Object> maps=new HashMap<String,Object>();
        if(WhetherEnum.YES.getValue().equals(lsq.getIsAct().getValue())&&ObjectUtil.isNull(lsq.getActId())){
             maps=leaderShowMapper.getRecentActId();
            lsq.setActId(Long.valueOf(maps.get("id").toString()));
            Map<String,Object> total = leaderShowMapper.saleNumberAndAmountByActId(lsq);
            map.put("payTotalAmount",total.get("totalAmount"));
            map.put("payNumber",total.get("payNumber"));
        }
        //总销  去除OrderStateEnum.REJECT 跟后台保持一致
        Map<String,Object> total = leaderShowMapper.saleNumberAndAmountReport(new LeaderSaleQuery(lsq.getAgentName(),
                lsq.getBeginDate(),lsq.getEndDate(),lsq.getOrderType(),null,null,null,OrderLogTypeEnum.AUDIT_PASS,null,lsq.getActId()));
        //断货 去除ProductStatusEnum.STATUS6 以log为准
        Map<String,Object> outStock = leaderShowMapper.saleNumberAndAmountReport(new LeaderSaleQuery(lsq.getAgentName(),
                lsq.getBeginDate(),lsq.getEndDate(),lsq.getOrderType(), null,null,null,OrderLogTypeEnum.STOCK_OUT,null,lsq.getActId()));
        //取消   去除ProductStatusEnum.STATUS7 以log为准
        Map<String,Object> cancel = leaderShowMapper.saleNumberAndAmountReport(new LeaderSaleQuery(lsq.getAgentName(),
                lsq.getBeginDate(),lsq.getEndDate(),lsq.getOrderType(),null,null,null,OrderLogTypeEnum.CANCEL,null,lsq.getActId()));
        //退货  去除AfterSalesTypeEnum.RETURN_GOODS  以log为准
        Map<String,Object> returned = leaderShowMapper.saleNumberAndAmountReport(new LeaderSaleQuery(lsq.getAgentName(),
                lsq.getBeginDate(),lsq.getEndDate(),lsq.getOrderType(),null, null,null,OrderLogTypeEnum.REFUND,null,lsq.getActId()));
        //计算利润值 总销 - 断货 - 取消 - 退货
        Map<String,Object> profit = new HashMap<>();
        if(total.get("saleTotalNum") != null
                && outStock.get("saleTotalNum") != null
                && cancel.get("saleTotalNum") != null
                && returned.get("saleTotalNum") != null){
            Long saleTotalNum = Long.valueOf(total.get("saleTotalNum").toString())
                                - Long.valueOf(outStock.get("saleTotalNum").toString())
                                - Long.valueOf(cancel.get("saleTotalNum").toString())
                                - Long.valueOf(returned.get("saleTotalNum").toString());
            profit.put("saleTotalNum",saleTotalNum);
        }else {
            profit.put("saleTotalNum",0);
        }
        if(total.get("saleTotalAmount") != null
                && outStock.get("saleTotalAmount") != null
                && cancel.get("saleTotalAmount") != null
                && returned.get("saleTotalAmount") != null){
            BigDecimal saleTotalAmount = new BigDecimal(total.get("saleTotalAmount").toString())
                                        .subtract(new BigDecimal(outStock.get("saleTotalAmount").toString()))
                                        .subtract(new BigDecimal(cancel.get("saleTotalAmount").toString()))
                                        .subtract(new BigDecimal(returned.get("saleTotalAmount").toString()));
            profit.put("saleTotalAmount",saleTotalAmount);
        }else {
            profit.put("saleTotalAmount",0);
        }
        map.put("total",total);
        map.put("outStock",outStock);
        map.put("cancel",cancel);
        map.put("returned",returned);
        map.put("profit",profit);
        map.put("actName",maps.get("actName"));
        return map;
    }

    @Override
    public IPage<Map<String, Object>> personalSaleReportList(Page page, LeaderSaleQuery leaderSaleQuery) {
        Map<String,Object> maps=new HashMap<String,Object>();
        if(WhetherEnum.YES.getValue().equals(leaderSaleQuery.getIsAct().getValue())&&ObjectUtil.isNull(leaderSaleQuery.getActId())){
            maps=leaderShowMapper.getRecentActId();
            leaderSaleQuery.setActId(Long.valueOf(maps.get("id").toString()));
        }
        IPage<Map<String, Object>> list = leaderShowMapper.personalSaleReportList(page,leaderSaleQuery);
        //计算退货百分比  退货数 / 总数 * 100
        calculatePercent(list);
        return list;
    }

    private void calculatePercent(IPage<Map<String, Object>> list){
        //计算退货百分比  退货数 / 总数 * 100
        if(list.getRecords() != null && list.getRecords().size() > 0){
            list.getRecords().forEach(m->{
                if(m.get("totalNum") != null && m.get("refundNum") != null
                        && new BigDecimal(m.get("totalNum").toString()).compareTo(BigDecimal.ZERO) != 0){
                    BigDecimal refundPercent = new BigDecimal(m.get("refundNum").toString())
                            .divide(new BigDecimal(m.get("totalNum").toString()),2,BigDecimal.ROUND_HALF_UP)
                            .multiply(new BigDecimal(100));
                    m.put("refundPercent",refundPercent);
                }else{
                    m.put("refundPercent",0);
                }
            });
        }
    }

    @Override
    public IPage<Map<String, Object>> teamSaleReportList(Page page, LeaderSaleQuery leaderSaleQuery) {
        Map<String,Object> maps=new HashMap<String,Object>();
        if(WhetherEnum.YES.getValue().equals(leaderSaleQuery.getIsAct().getValue())&&ObjectUtil.isNull(leaderSaleQuery.getActId())){
            maps=leaderShowMapper.getRecentActId();
            leaderSaleQuery.setActId(Long.valueOf(maps.get("id").toString()));
        }
        IPage<Map<String, Object>> list = leaderShowMapper.teamSaleReportList(page,leaderSaleQuery);
        //计算退货百分比  退货数 / 总数 * 100
        calculatePercent(list);
        return list;
    }

    @Override
    public IPage<OrderShowVo> saleReportOrderList(Page initMpPage, LeaderSaleOrderListQuery leaderSaleQuery) {
        if(leaderSaleQuery.getTeamOrPerson().equals(0)){//0代表团队
           return   leaderShowMapper.saleTeamOrderList(initMpPage,leaderSaleQuery);
        }else if(leaderSaleQuery.getTeamOrPerson().equals(1)){//1代表个人
           return leaderShowMapper.salePrsonOrderList(initMpPage,leaderSaleQuery);
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getStockSkuList(LeaderStockQuery lsq) {
        List<Map<String, Object>> result=leaderShowMapper.getStockSkuList(lsq);
        for(Map<String, Object> objectMap:result ){
            objectMap.put("color", SKUUtils.color2(objectMap.get("sku").toString()));
            objectMap.put("szie", SKUUtils.size2(objectMap.get("sku").toString()));
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> actList(Integer type) {
        Date dateTime = DateUtil.offset(new Date(), DateField.YEAR, -1);
        return leaderShowMapper.actList(dateTime,type);
    }

    /**
     * 代理商团队列表
     * @return
     */
    @Override
    public IPage<Map<String, Object>> teamList(Page initMpPage,LeaderAgentQuery query) {
        return leaderShowMapper.agentList(initMpPage,query);
    }

    @Override
    public IPage<Map<String, Object>> agentRenewList(Page initMPage, LeaderAgentReNewQuery agentQuery) {
        return leaderShowMapper.agentRenewList(initMPage,agentQuery);
    }

    @Override
    public IPage<Map<String, Object>> getBuyList(Page initMpPage, LeaderMemberQuery leaderMemberQuery) {
        IPage<Map<String, Object>> buyList=leaderShowMapper.getBuyList(initMpPage,leaderMemberQuery);
        for(Map<String, Object> map:buyList.getRecords()){
            map.put("sysTag", EnumUtil.getIEnum(OrderSysTagEnum.class, map.get("sysTag").toString()));
        }
        return buyList;

    }

    @Override
    public List<Map<String, Object>> getSaleFxList() {
        return leaderShowMapper.getSaleFxList();
    }

    @Override
    public List<Map<String, Object>> adsLabel() {
        return leaderShowMapper.adsLabel();
    }

    /**
     * 领导看板销售总量订单列表
     * @param leaderShowOrderQuery
     * @return
     */
    @Override
    public List<Map<String, Object>> orderSaleListForLeader(Page initMpPage,LeaderShowOrderQuery leaderShowOrderQuery) {
        List<Map<String, Object>>  result=leaderShowMapper.orderSaleListForLeader(initMpPage,leaderShowOrderQuery);
        if(ObjectUtil.isNotEmpty(result)){
            for(Map<String, Object> tt:result){
                Integer sysTag=Integer.valueOf(tt.get("sysTag").toString());
                Integer appTag=Integer.valueOf(tt.get("appTag").toString());
                for(OrderAppTagEnum orderAppTagEnum: OrderAppTagEnum.values()){
                    if(appTag.intValue()==orderAppTagEnum.getValue().intValue()){
                        tt.put("appTag",orderAppTagEnum.getDesp());
                    }

                }
                for(OrderSysTagEnum orderSysTagEnum: OrderSysTagEnum.values()) {
                    if(sysTag.intValue()==orderSysTagEnum.getValue().intValue()){
                        tt.put("sysTag",orderSysTagEnum.getDesp());
                    }
                }
            }
        }
        return result;
    }


}
